package main

import (
	"fmt"
	"net"
	"time"
)

func main() {
	srvAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:8003")
	if err != nil {
		fmt.Println("resolveudpaddr error", err)
		return
	}

	udpConn, err := net.ListenUDP("udp", srvAddr)
	if err != nil {
		fmt.Println("listenudp error", err)
		return
	}
	defer udpConn.Close()
	fmt.Println("udp socket创建完成...")

	for {
		buf := make([]byte, 4096)
		n, cliAddr, err := udpConn.ReadFromUDP(buf)
		if err != nil {
			fmt.Println("readfromudp error", err)
			return
		}
		fmt.Printf("服务器读到%v的数据：%s\n", cliAddr, string(buf[:n]))

		//daytime := time.Now().String()
		timeStr:=time.Now().Format("2006-01-02 15:04:05")
		fmt.Println(timeStr)
		_, err1 := udpConn.WriteToUDP([]byte(timeStr+"\n"), cliAddr)
		if err1 != nil {
			fmt.Println("write to udp error:", err1)
			return
		}
	}
}
